<?php


namespace app\controller;

use app\model\User;
use app\tools\ResponseTool;
use app\validate\user\UserLogin;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Request;
class Login extends MyBaseController
{
    //登陆
    public function login() {
        $userInfo = new User(Request::param());
        switch ($userInfo->stat) {
            case 'user':
                try {
                    validate(UserLogin::class)->check([
                        'user_name'     =>  $userInfo->userName,
                        'user_password' =>  $userInfo->userPassword,
                    ]);
                } catch (ValidateException $e) {
                    return ResponseTool::getRs('PARAM_ERROR', [], $e->getError());
                }
                $getPassword = $userInfo->userPassword;
                $selInfo = $userInfo->where('user_name', $userInfo->userName)->findOrEmpty();
                if (!$selInfo->isEmpty() && $getPassword == $selInfo->user_password) {
                    $userToken = uniqid();
                    Cache::set($userInfo->userName, $userToken, 3600);
                    return ResponseTool::getRs('OK', [
                        'userToken' => $userToken,
                        'userName'  => $userInfo->userName
                    ], '');
                } else {
                    return ResponseTool::getRs('PARAM_ERROR', [], '您输入的密码不正确');
                }
                break;
            case 'tel':
                $telNum = Request::param('telNum');
                $validateCode = Request::param('validateCode');
                $userInfo = new User();
                $selInfo = $userInfo->where('tel_num', $telNum)->findOrEmpty();
//                Log::record($selInfo->user_name);
                Log::record(Cache::get($selInfo->user_name));
                if ($selInfo->isEmpty()) {
                    return ResponseTool::getRs('PARAM_ERROR',  [], '你的手机号尚未注册');
                } else {
                    if ($validateCode && $validateCode == Cache::get($telNum)) {
                        if (Cache::get($selInfo->user_name)) {
                            $userToken = Cache::get($selInfo->user_name);
                        } else {
                            $userToken = uniqid();
                            Cache::set($selInfo->userName, $userToken, 3600);
                        }
                        return ResponseTool::getRs('OK', [
                            'userName' => $selInfo->user_name,
                            'userToken' => $userToken,
                        ], '');
                    } else {
                        return ResponseTool::getRs('PARAM_ERROR', [], '短信验证码过期或失效');
                    }
                }
                break;
        }
    }

    //test
    public function test() {
        var_dump(Cache::get('haoshen'));
    }
}